package com.lemon.soft.bookingroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lemon.soft.bookingroom.dao.BookingsDao;
import com.lemon.soft.bookingroom.dao.RoomTimeStatusDao;
import com.lemon.soft.bookingroom.dao.UsersDao;
import com.lemon.soft.bookingroom.dto.CancellationDTO;
import com.lemon.soft.bookingroom.entity.BookingsEntity;
import com.lemon.soft.bookingroom.entity.RoomTimeStatusEntity;
import com.lemon.soft.bookingroom.entity.UsersEntity;
import com.lemon.soft.bookingroom.service.MeetingRoomsService;
import com.lemon.soft.bookingroom.util.PageUtils;
import com.lemon.soft.bookingroom.util.Query;
import com.lemon.soft.bookingroom.util.R;
import com.lemon.soft.bookingroom.vo.BookingVo;
import com.lemon.soft.bookingroom.vo.CancelVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.lemon.soft.bookingroom.dao.CancellationRecordsDao;
import com.lemon.soft.bookingroom.entity.CancellationRecordsEntity;
import com.lemon.soft.bookingroom.service.CancellationRecordsService;


@Service("cancellationRecordsService")
public class CancellationRecordsServiceImpl extends ServiceImpl<CancellationRecordsDao, CancellationRecordsEntity> implements CancellationRecordsService {
    @Autowired
    private MeetingRoomsService meetingRoomsService;
    @Autowired
    private BookingsDao bookingService;
    @Autowired
    private UsersDao userService;

    @Autowired
    private RoomTimeStatusDao roomTimeStatusService;
    @Override
    public R queryPage() {
        LambdaQueryWrapper<CancellationRecordsEntity> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(CancellationRecordsEntity::getReviewStatus,0);
        List<Object> collect = this.list(queryWrapper).stream().map(entity -> {
            CancelVo cancelVo = new CancelVo();
            BeanUtils.copyProperties(entity, cancelVo);

            BookingsEntity bookingsEntity = bookingService.selectById(entity.getBookingId());

            BookingVo bookingVo = new BookingVo();
            BeanUtils.copyProperties(bookingsEntity, bookingVo);
            bookingVo.setRoomName(meetingRoomsService.getById(bookingsEntity.getRoomId()).getRoomName());

            cancelVo.setBookingVo(bookingVo);

            UsersEntity usersEntity = userService.selectById(bookingsEntity.getUserId());
            cancelVo.setUserName(usersEntity.getName());
            return cancelVo;

        }).collect(Collectors.toList());
        return R.ok().put("data",collect);
    }

    @Override
    public String applyCancellation(CancellationDTO cancellationDTO, Integer userId) {

        BookingsEntity booking = bookingService.selectById(cancellationDTO.getBookingId());
         // 1. 检查用户是否为订单所有者
        if (booking == null || !booking.getUserId().equals(userId)) {
            //TODO
//            throw new BusinessException("无权取消此订单");
            return "无权取消此订单";
        }


        // 2. 检查订单状态
        if (booking.getPaymentStatus() != 1) {
            //TODO
           // throw new BusinessException("订单状态异常，无法取消");
            return "订单状态异常，无法取消";
        }
        //检查是否已申请
        LambdaQueryWrapper<CancellationRecordsEntity> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(CancellationRecordsEntity::getBookingId,cancellationDTO.getBookingId());
         CancellationRecordsEntity entity = this.getOne(queryWrapper);
        if(entity!=null){
            //TODO
            return "已申请取消";
        }

        // 3. 检查是否超过取消时间限制（需提前24小时申请）
        // 获取预订开始时间和取消时间
        LocalDateTime bookingStartTime = booking.getStartTime();
        LocalDateTime cancelTime = cancellationDTO.getCancelTime();

      // 计算时间差（小时）
        Duration duration = Duration.between(cancelTime, bookingStartTime);
        long cancelAdvance = duration.toHours();
        if (cancelAdvance < 24) {
            //TODO
            //throw new BusinessException("取消预订需提前24小时申请");
            return "取消预订需提前24小时申请";
        }

        // 4. 计算退款金额
        BigDecimal refundAmount = calculateRefundAmount(cancellationDTO.getBookingId(), cancellationDTO.getCancelTime());

        // 5. 创建取消预订记录
        CancellationRecordsEntity record = new CancellationRecordsEntity();
        record.setBookingId(cancellationDTO.getBookingId());
        record.setUserId(userId);
        record.setCancelTime(cancellationDTO.getCancelTime());
        record.setCancelReason(cancellationDTO.getCancelReason());
        record.setRefundAmount(refundAmount);
        record.setReviewStatus(0); // 待审核
        record.setCreateTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        record.setIsDelete(0);

        this.save(record);

        return "取消预订申请已提交，请等待审核";
    }

    @Override
    public BigDecimal calculateRefundAmount(Integer bookingId, LocalDateTime cancelTime) {

        // 1. 查询订单信息
        BookingsEntity booking = bookingService.selectById(bookingId);

        // 计算时间差（小时）
        Duration duration = Duration.between(cancelTime, booking.getStartTime());
        long cancelAdvance = duration.toHours();
        // 3. 根据退款规则计算退款比例
        BigDecimal refundRate;
        if (cancelAdvance >= 72) {
            refundRate = new BigDecimal("1.0"); // 100% 退款
        } else if (cancelAdvance >= 48) {
            refundRate = new BigDecimal("0.75"); // 75% 退款
        } else if (cancelAdvance >= 24) {
            refundRate = new BigDecimal("0.25"); // 25% 退款
        } else {
            refundRate = BigDecimal.ZERO; // 少于24小时，不予退款
        }

        // 4. 计算退款金额
        return booking.getTotalPrice().multiply(refundRate).setScale(2, RoundingMode.HALF_UP);
    }

    @Override
    public String reviewCancellation(Integer cancellationId, Integer staffId, Integer reviewStatus, String reviewRemark) {
        // 1. 检查员工是否存在
        UsersEntity staff = userService.selectById(staffId);
        if (staff == null || staff.getIsDelete() == 1) {
//            TODO
//            throw new BusinessException("员工不存在");
            return "员工不存在";
        }

        // 2. 检查取消记录是否存在
        CancellationRecordsEntity record = this.getById(cancellationId);
        if (record == null || record.getIsDelete() == 1) {
//            TODO
//            throw new BusinessException("取消记录不存在");
            return "取消记录不存在";
        }

        // 3. 审核取消申请
        record.setStaffId(staffId);
        record.setReviewStatus(reviewStatus);
        record.setReviewRemark(reviewRemark);
        record.setReviewTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        this.updateById(record);

        // 4. 如果审核通过，处理退款和释放会议室
        if (reviewStatus == 1) { // 已通过
            BookingsEntity booking = bookingService.selectById(record.getBookingId());
            if (booking != null) {
                booking.setPaymentStatus(2); // 已取消
                booking.setUpdateTime(LocalDateTime.now());
                bookingService.updateById(booking);
            }

            // 更新会议室状态为空闲
            QueryWrapper<RoomTimeStatusEntity> statusQuery = new QueryWrapper<>();
            statusQuery.eq("booking_id", record.getBookingId())
                    .eq("is_delete", 0);
            RoomTimeStatusEntity roomTimeStatus = roomTimeStatusService.selectOne(statusQuery);

            if (roomTimeStatus != null) {
                roomTimeStatus.setStatus("空闲");
                roomTimeStatus.setBookingId(null);
                roomTimeStatus.setUpdateTime(LocalDateTime.now());
                roomTimeStatusService.updateById(roomTimeStatus);
            }
        }

        return "取消预订审核已处理";
    }

}